package com.xj.admin.config;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author ruanzh
 * @since 2017/8/25
 */
@Controller
public class ErrorInterceptor implements HandlerInterceptor {
    
    private Logger logger = LoggerFactory.getLogger(ErrorInterceptor.class);
    
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse httpServletResponse, Object o) throws Exception {
        logger.info(">>>MyInterceptor1>>>>>>>在ErrorInterceptor请求处理之前进行调用（Controller方法调用之前）");
        logger.info("   request uri：" + request.getRequestURI());
        return true;// 只有返回true才会继续向下执行，返回false取消当前请求
    }
    
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object o, ModelAndView modelAndView) throws Exception {
        logger.info(">>>MyInterceptor1>>>>>>>请求处理之后进行调用，但是在视图被渲染之前（Controller方法调用之后）");
        if (response.getStatus() == 500) {
            modelAndView.setViewName("/errorpage/500");
        } else if (response.getStatus() == 404) {
//            modelAndView.setViewName("/errorpage/404");
            logger.error(request.getRequestURI() + " Not Found");
        }
    }
    
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
        logger.info(">>>MyInterceptor1>>>>>>>在整个请求结束之后被调用，也就是在DispatcherServlet 渲染了对应的视图之后执行（主要是用于进行资源清理工作）");
    }
}
